from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from rest_framework.authentication import BaseAuthentication, TokenAuthentication
from rest_framework import exceptions

from django.conf import settings
from apps import redis_client
from apps.user.models import User


class OWNTokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get("HTTP_X_ACCESS_TOKEN")
        if token:
            try:
                yuan_info = self.de_ser(token)
                expire_token = redis_client.get("".join(["username_", yuan_info.get("username")]))
                if expire_token:
                    if token == expire_token.decode("utf-8"):
                        raise exceptions.AuthenticationFailed({"code": 401, "msg": '没有令牌或令牌过期'})
            except Exception as e:
                raise exceptions.AuthenticationFailed({"code": 401, "msg": '没有令牌或令牌过期'})
            username = yuan_info.get("username")
            user = User.objects.filter(username=username, is_delete=False, is_active=True).first()
            if not user:
                raise exceptions.AuthenticationFailed({"code": 401, "msg": '用户不存在'})
        else:
            raise exceptions.AuthenticationFailed({"code": 401, "msg": '没有令牌或令牌过期'})

    def de_ser(self, mi_info):
        serializer = Serializer(settings.SECRET_KEY, settings.TOKEN_TIME)
        yuan_info = serializer.loads(mi_info)
        return yuan_info

    def authenticate_header(self, request):
        pass
